package com.dean.practice.producer.service;

import cn.himygirl.dk.common.utils.Prediction;
import cn.himygirl.dk.uaa.core.DnAuthUser;
import cn.himygirl.dk.uaa.oauth.server.DnUserRetrieveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 默认的示例授权用户处理器
 *
 * @author fuhw/Dean
 * @date 2020-09-11
 */
@Service
public class UserRetrieveSampleImpl implements DnUserRetrieveService {

    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserRetrieveSampleImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public DnAuthUser loadUserByUsername(String username) throws UsernameNotFoundException {
        Prediction.assertTrueThrow(Objects.equals(username, "deanName"),
                new UsernameNotFoundException("user not found by name:" + username));
        return new DnAuthUser(10, "deanName",
                passwordEncoder.encode("deanPwd"),
                true,
                true,
                true,
                true,
                Stream.of("ROLE_001", "ROLE_002", "ROLE_USER").map(SimpleGrantedAuthority::new).collect(Collectors.toSet())
        );
    }

    @Override
    public DnAuthUser loadUserByMobile(String mobile) throws UsernameNotFoundException {
        Prediction.assertTrueThrow(Objects.equals(mobile, "13100000000"),
                new UsernameNotFoundException("user not found by mobile:" + mobile));
        return new DnAuthUser(12, mobile,
                passwordEncoder.encode("deanPwd"),
                true,
                true,
                true,
                true,
                Stream.of("ROLE_001", "ROLE_003", "ROLE_ADMIN").map(SimpleGrantedAuthority::new).collect(Collectors.toSet())
        );
    }

    @Override
    public boolean checkCaptchaByMobile(String mobile, String captcha) {
        return true;
    }
}
